import httpx
from typing import Optional, Dict, Any
from pydantic import BaseModel

class HttpClient:
    """封装异步HTTP客户端，用于服务间通信"""
    def __init__(self, base_url: str):
        self.base_url = base_url
        self.client = httpx.AsyncClient(base_url=base_url, timeout=10.0) # 统一设置超时

    async def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
        """发送GET请求"""
        response = await self.client.get(path, params=params)
        response.raise_for_status()  # 自动处理4xx/5xx错误
        return response.json()

    async def post(self, path: str, data: Optional[BaseModel] = None) -> Any:
        """发送POST请求（支持Pydantic模型）"""
        json_data = data.model_dump() if data else None
        response = await self.client.post(path, json=json_data)
        response.raise_for_status()
        return response.json()

    async def close(self):
        """关闭客户端连接"""
        await self.client.aclose()

# 使用示例（在其他服务中）：
# client = HttpClient("http://user-service:8001")
# user = await client.get("/users/1")
